package com.szzg10.webservice.chapter5;

import java.io.IOException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SunTrustingClient {
	
	public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException {
		new SunTrustingClient().doIt();
	}
	
	private void doIt() throws NoSuchAlgorithmException, IOException, KeyManagementException {
		TrustManager[] trustManagers = getTrustManager();
		
		SSLContext sslContext = SSLContext.getInstance("SSL");
		sslContext.init(null, trustManagers, new SecureRandom());
		
		HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
		
		URL url = new URL("https://www.google.com.hk");
		
		HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.connect();
		
		dump_features(conn);
	}
	
	private TrustManager[] getTrustManager() {
		TrustManager[] trustManagers = new TrustManager[] {
			new X509TrustManager() {
				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
				
				@Override
				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
				
				@Override
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
			}			
		};
		
		return trustManagers;
	}
	
	private void dump_features(HttpsURLConnection conn) throws IOException {
		System.out.println("Status code: " + conn.getResponseCode());
		System.out.println("Cipher Suite: " + conn.getCipherSuite());
		System.out.println();
		
		Certificate[] certificates = conn.getServerCertificates();
		for(Certificate element: certificates) {
			System.out.println("Type: " + element.getType());
			System.out.println("Hash Code: " + element.hashCode());
			System.out.println("Algorithm: " + element.getPublicKey().getAlgorithm());
			System.out.println("Format: " + element.getPublicKey().getFormat());
			System.out.println();
		}
	}
	
}
